# Copyright 2022 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

{!{- $workflowName              := "Weekly CVE tests" -}!}
{!{- $enableWorkflowOnTestRepos := true -}!}
{!{- $testAllReleaseChannels    := true -}!}


{!{ define "cve_tests" }!}
# <template: cve_tests>
- name: Checking out candi/image_versions.yml
  run: |
    echo "⚓️ 📤 Checking out candi/image_versions.yml from ${TAG}..."
    git checkout --force "${TAG}" -- candi/image_versions.yml
- name: Run base images CVE tests on ${{env.TAG}}
  run: |
    echo "⚓️ 🏎 Running CVE tests on ${TAG}..."
    make cve-base-images
- name: Run Deckhouse images CVE tests on ${{env.TAG}}
  run: |
    echo "⚓️ 🏎 Running Deckhouse images CVE tests on ${TAG}..."
    make cve-report
- name: Rename report artifacts
  if: success()
  run: |
    mv "out/base-images.html" "out/${TAG}_base-images.html"
    mv "out/d8-images.html" "out/${TAG}_d8-images.html"
- name: Create fail artifact
  if: failure()
  run: |
    echo "Trivy tests for ${TAG} have failed." > "out/${TAG}_test-failed.txt"
- name: Upload report artifacts
  if: success()
  uses: {!{ index (ds "actions") "actions/upload-artifact" }!}
  with:
    name: cve-reports
    path: |
      out/${{ env.TAG }}_base-images.html
      out/${{ env.TAG }}_d8-images.html
- name: Upload fail artifact
  if: failure()
  uses: {!{ index (ds "actions") "actions/upload-artifact" }!}
  with:
    name: cve-reports
    path: |
      out/${{ env.TAG }}_test-failed.txt
# </template: cve_tests>
{!{- end -}!}

{!{- $ctx := . }!}

name: '{!{ $workflowName }!}'
on:
  schedule:
  - cron: '0 23 * * 5'
  workflow_dispatch:

concurrency:
  group: cve-daily

jobs:
  skip_tests_repos:
    name: Skip tests repos
    runs-on: ubuntu-latest
    if: ${{ {!{ $enableWorkflowOnTestRepos }!} || github.repository == 'deckhouse/deckhouse' }}
    steps:
    - name: Do nothing
      run: echo "Empty action to fulfil Github requirements."

  fetch_tags_for_test:
    name: Fetch release channel tags
    runs-on: ubuntu-latest
    needs:
      - skip_tests_repos
    steps:
{!{- tmpl.Exec "checkout_full_step" $ctx | strings.Indent 6 }!}
      - name: Generate tag => channel matrix
        id: tag_matrix
        run: echo "tag_matrix=$(tools/cve/tag_map.sh)" >> $GITHUB_OUTPUT
    outputs:
      tag_matrix: ${{ steps.tag_matrix.outputs.tag_matrix }}

  test_cve_report_main:
    name: Main
    needs:
      - skip_tests_repos
    runs-on: [ self-hosted, regular ]
    env:
      IMAGE: "dev-registry.deckhouse.io/sys/deckhouse-oss"
      TAG: "main"
    steps:
{!{ tmpl.Exec "checkout_full_step"           $ctx | strings.Indent 6 }!}
{!{ tmpl.Exec "login_dev_registry_step"      $ctx | strings.Indent 6 }!}
{!{ tmpl.Exec "login_readonly_registry_step" $ctx | strings.Indent 6 }!}
{!{ tmpl.Exec "link_bin_step"                     | strings.Indent 6 }!}
{!{ tmpl.Exec "cve_tests"                         | strings.Indent 6 }!}
{!{ tmpl.Exec "unlink_bin_step"                   | strings.Indent 6 }!}

{!{ if $testAllReleaseChannels }!}
  test_cve_report_channels:
    name: ${{ matrix.tag }}
    needs:
      - fetch_tags_for_test
    strategy:
      fail-fast: false
      matrix:
        tag: ${{ fromJson(needs.fetch_tags_for_test.outputs.tag_matrix) }}
    runs-on: [ self-hosted, regular ]
    steps:
  {!{ tmpl.Exec "checkout_full_step"           $ctx | strings.Indent 6 }!}
  {!{ tmpl.Exec "login_dev_registry_step"      $ctx | strings.Indent 6 }!}
  {!{ tmpl.Exec "login_readonly_registry_step" $ctx | strings.Indent 6 }!}
  {!{ tmpl.Exec "link_bin_step"                     | strings.Indent 6 }!}
      - name: Set repo and tag for matrix run
        env:
          matrix_tag: ${{ matrix.tag }}
        run: |
          echo "IMAGE=registry.deckhouse.io/deckhouse/fe" >> $GITHUB_ENV
          echo "TAG=$(echo "${matrix_tag}" | grep -Eo "^\S+")" >> $GITHUB_ENV
  {!{ tmpl.Exec "cve_tests"                         | strings.Indent 6 }!}
  {!{ tmpl.Exec "unlink_bin_step"                   | strings.Indent 6 }!}
{!{- end }!}

#   send-email-report:
#     name: Send weekly report
#     needs:
#       - test_cve_report_main
# {!{- if $testAllReleaseChannels }!}
#       - test_cve_report_channels
# {!{- end }!}
#     if: success() || failure()
#     runs-on: [ self-hosted, regular ]
#     steps:
#       - name: Clear output directory
#         run: |
#           rm -rf out/
#       - name: Download reports artifact
#         uses: {!{ index (ds "actions") "actions/download-artifact" }!}
#         with:
#           name: cve-reports
#           path: out/
#       - name: Create report archive
#         working-directory: out/
#         run: |
#           zip -r cve-reports.zip ./*
#       - name: Send report
#         env:
#           MAIL_API_TOKEN: ${{ secrets.MAIL_API_TOKEN }}
#           MAIL_API_URL: ${{ secrets.MAIL_API_URL }}
#           MAIL_API_TRIVY_SENDER: ${{ secrets.MAIL_API_TRIVY_SENDER }}
#           MAIL_API_TRIVY_RECEIVER: ${{ secrets.MAIL_API_TRIVY_RECEIVER }}
#         run: |
#           curl -s --user "${MAIL_API_TOKEN}" \
#             "${MAIL_API_URL}" \
#             -F from="${MAIL_API_TRIVY_SENDER}" \
#             -F to="${MAIL_API_TRIVY_RECEIVER}" \
#             -F subject='Trivy reports' \
#             -F text='Hello! There are Weekly Trivy scan reports attached to this message.' \
#             -F attachment=@out/cve-reports.zip
#       - name: Clear output directory
#         run: |
#           rm -rf out/